import java.util.HashMap;
import java.util.Map;

public class Solution1315 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    Map<TreeNode,TreeNode> map=new HashMap<>();

    public int sumEvenGrandparent(TreeNode root) {
        if (root==null){
            return 0;
        }
        int add=0;
        if (map.containsKey(root) && map.containsKey(map.get(root)) && map.get(map.get(root)).val%2==0){
            add=root.val;
        }
        if (root.left!=null){
            map.put(root.left,root);
        }
        if (root.right!=null){
            map.put(root.right,root);
        }
        return add+sumEvenGrandparent(root.left)+sumEvenGrandparent(root.right);
    }

    public static void main(String[] args) {
        System.out.println(new Solution1315().sumEvenGrandparent(new TreeNode(6,new TreeNode(7,new TreeNode(2,new TreeNode(9),null),new TreeNode(7,new TreeNode(1),new TreeNode(4))),new TreeNode(8,new TreeNode(1),new TreeNode(3,null,new TreeNode(5))))));
    }
}
